import GeoJSON from 'ol/format/GeoJSON'
import { Stroke, Style } from 'ol/style'
import { TyFeatureLayer } from '@/plugin/map/tyMapUtlis'

export const PoiMixin = {
  props: {
    layerPois: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  watch: {
    layerPois: {
      handler() {
        this.showPoiLayer()
      }
    }
  },
  data() {
    return {
      poiFeatures: [],
      poiFeatureLayer: null
    }
  },
  methods: {
    showPoiLayer(poiFeatures = this.layerPois, markers = [], isFit) {
      this.poiFeatures = []
      const format = new GeoJSON({})
      poiFeatures.forEach((item, index) => {
        item.coordinates = item.geometry.coordinates
        const showIndex = Math.ceil(item.geometry.coordinates[0].length / 2)
        item.coordinates = item.geometry.coordinates[0][showIndex]
        const feature = format.readFeature(item.geometry)
        feature.setStyle(new Style({
          stroke: new Stroke({
            color: 'rgba(64,158,255,0.7)',
            width: 10
          }),
          zIndex: 3000 + index
        }))
        this.poiFeatures.push(feature)
        item.title = item.properties.name
        item.clickType = 'poi'
        item.animate = true
        delete item.geometry
        markers.push(item)
      })
      this.createPoiLayer(isFit)
      this.showMarkerFeature(markers, true, 'poi')
    },
    createPoiLayer(isFit = true) {
      if (this.poiFeatureLayer === null) {
        this.poiFeatureLayer = new TyFeatureLayer(this.option)
      }
      this.poiFeatureLayer.clear()
      this.poiFeatureLayer.addFeatures(this.poiFeatures)
      if (this.poiFeatures.length > 0 && isFit) {
        this.map.fitByFeatures(this.poiFeatureLayer.getFeatures())
      }
      return this.poiFeatureLayer.getFeatures()
    },
    clearPoiLayer() {
      if (this.poiFeatureLayer !== null) {
        this.poiFeatureLayer.clear()
      }
    }

  }
}
